#include "lichenfindpacket.h"
#include "misc.h"
#include <QDateTime>

LiChenFindPacket::LiChenFindPacket(QObject *parent)
    : BaseFindPacket (parent)
{

}

LiChenFindPacket::~LiChenFindPacket()
{

}

QList<ProtocolPacket> LiChenFindPacket::find(const QByteArray &data)
{
    m_rxBuffer.append(data);

    QList<ProtocolPacket>   packets;
    while (!m_rxBuffer.isEmpty())
    {
        char _data = m_rxBuffer.at(0);
        m_rxBuffer.remove(0, 1);//移除头字节

        switch (m_state)
        {
            case 0:
                if (_data == 'K')
                {
                    m_rxPacket.clear();
                    m_rxPacket.append(_data);
                    m_state = 1;
                }
                break;
            case 1:
                m_rxPacket.append(_data);

                if (_data == '\r') // 帧尾必须为"\r\n"
                {
                    if (m_rxPacket.size() == 15) // 第15个字节为'\r'
                        m_state = 2;
                    else
                        m_state = 0;
                }
                break;
            case 2:
                m_rxPacket.append(_data);

                if (_data == '\n') // 帧尾正确
                {
                    ProtocolPacket packet;
//                    packet.timestamp = Misc::getTimeStamp();
                    packet.timestamp = QDateTime::currentMSecsSinceEpoch();
                    packet.buffer = m_rxPacket;
                    packets << packet;
                }
                else // 帧尾不对
                {

                }

                m_state = 0;
                break;
            default:
                m_state = 0;
                break;
        }
    } // while

    return packets;
}
